package com.yunhe.option.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.option.domain.base.PaymentStatus;
import com.yunhe.option.repository.base.PaymentStatusRepository;
import com.yunhe.option.service.base.PaymentStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 企业缴费情况Service
 * @desc 企业缴费情况服务类实现
 * @author anmeiyi
 */
@Service
public class PaymentStatusServiceImpl implements PaymentStatusService {
    @Autowired
    private PaymentStatusRepository paymentStatusRepository;

    private void processBeforeSave(PaymentStatus paymentStatus)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断企业缴费情况代码、编号、标题是否为空
        if(paymentStatus.getCode() == null
                || StringUtil.isEmpty(paymentStatus.getName())
                || StringUtil.isEmpty(paymentStatus.getTitle())) {
            throw new ArgumentErrorException("企业缴费情况代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        PaymentStatus categoryByCode = this.findByCode(paymentStatus.getCode());
        if(categoryByCode != null) {
            if(paymentStatus.getId() == null || categoryByCode.getId().longValue() != paymentStatus.getId().longValue()) {
                throw new UniqueConstraintsException("该企业缴费情况代码已存在");
            }
        }
        //判断编号是否已存在
        PaymentStatus categoryByName = this.findByName(paymentStatus.getName());
        if(categoryByName != null) {
            if(paymentStatus.getId() == null || categoryByName.getId().longValue() != paymentStatus.getId().longValue()) {
                throw new UniqueConstraintsException("该企业缴费情况编号已存在");
            }
        }
        //如果序号为空，则默认等于代码
        if(paymentStatus.getSn() == null && paymentStatus.getCode() != null) {
            paymentStatus.setSn(paymentStatus.getCode());
        }
    }

    /**
     * 新增企业缴费情况
     * @param paymentStatus 企业缴费情况对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public PaymentStatus createPaymentStatus(PaymentStatus paymentStatus)
            throws ArgumentErrorException, UniqueConstraintsException {
        paymentStatus.setId(null);
        processBeforeSave(paymentStatus);
        return paymentStatusRepository.save(paymentStatus);
    }

    /**
     * 删除企业缴费情况
     * @param paymentStatusId 企业缴费情况Id
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deletePaymentStatus(Long paymentStatusId) {
        paymentStatusRepository.deleteById(paymentStatusId);
    }

    /**
     * 更新企业缴费情况(全部字段）
     * @param paymentStatus 企业缴费情况对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public PaymentStatus updatePaymentStatus(PaymentStatus paymentStatus)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = paymentStatus.getId() != null && paymentStatusRepository.existsById(paymentStatus.getId());
        if(!exists) {
            throw new ObjectNotFoundException("找不到ID为" + paymentStatus.getId() + "的企业缴费情况");
        }
        processBeforeSave(paymentStatus);
        return paymentStatusRepository.save(paymentStatus);
    }

    /**
     * 更新企业缴费情况（部分字段）
     * @param paymentStatusId 企业缴费情况对象
     * @param code
     * @param name
     * @param title
     * @param sn
     * @param activity
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public PaymentStatus updatePaymentStatus(Long paymentStatusId, Long code, String name, String title, Long sn, Boolean activity)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        PaymentStatus paymentStatus = this.findByPaymentStatusId(paymentStatusId);
        if(paymentStatus == null) {
            throw new ObjectNotFoundException("找不到ID为" + paymentStatusId + "的企业缴费情况");
        }
        Optional.ofNullable(code).ifPresent(paymentStatus::setCode);
        Optional.ofNullable(name).ifPresent(paymentStatus::setName);
        Optional.ofNullable(title).ifPresent(paymentStatus::setTitle);
        Optional.ofNullable(sn).ifPresent(paymentStatus::setSn);
        Optional.ofNullable(activity).ifPresent(paymentStatus::setActivity);
        processBeforeSave(paymentStatus);
        return paymentStatusRepository.save(paymentStatus);
    }

    /**
     * 获得全部企业缴费情况对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Iterable<PaymentStatus> findIndustryCategories() {
        return paymentStatusRepository.findAll(QueryUtil.defaultSort());
    }

    /**
     * 根据编号获得企业缴费情况对象
     * @param name
     */
    private PaymentStatus findByName(String name) {
        return paymentStatusRepository.findByName(name);
    }

    /**
     * 根据代码获得企业缴费情况对象
     * @param code
     */
    private PaymentStatus findByCode(Long code) {
        return paymentStatusRepository.findByCode(code);
    }

    /**
     * 根据ID获得企业缴费情况对象
     * @param paymentStatusId
     * @return
     */
    private PaymentStatus findByPaymentStatusId(Long paymentStatusId) {
        return paymentStatusRepository.findById(paymentStatusId).orElse(null);
    }
}
